<template>
  <div class="task-log-container">
    <!-- 搜索区域 -->
    <el-card shadow="never" class="search-card">
      <el-form :model="searchForm" label-width="100px">
        <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item label="任务名称">
              <el-input v-model="searchForm.taskName" placeholder="请输入任务名称" clearable />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="执行状态">
              <el-select v-model="searchForm.status" placeholder="请选择状态" clearable>
                <el-option label="成功" value="SUCCESS" />
                <el-option label="失败" value="FAILED" />
                <el-option label="运行中" value="RUNNING" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="执行时间">
              <el-date-picker
                v-model="searchForm.executeTimeRange"
                type="daterange"
                range-separator="至"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
                value-format="YYYY-MM-DD"
              />
            </el-form-item>
          </el-col>
          <el-col :span="24" style="text-align: right;">
            <el-button type="primary" @click="handleSearch">搜索</el-button>
            <el-button @click="resetSearch">重置</el-button>
          </el-col>
        </el-row>
      </el-form>
    </el-card>

    <!-- 表格区域 -->
    <el-card shadow="never">
      <el-table
        :data="tableData"
        border
        style="width: 100%"
        v-loading="loading"
      >
        <el-table-column prop="id" label="ID" width="80" />
        <el-table-column prop="taskName" label="任务名称" min-width="180" />
        <el-table-column prop="startTime" label="开始时间" width="180" />
        <el-table-column prop="endTime" label="结束时间" width="180" />
        <el-table-column prop="duration" label="耗时(秒)" width="120" />
        <el-table-column prop="status" label="状态" width="120">
          <template #default="{ row }">
            <el-tag :type="statusTagType(row.status)">
              {{ formatStatus(row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="message" label="执行结果" min-width="200" show-overflow-tooltip />
        <el-table-column label="操作" width="120" fixed="right">
          <template #default="{ row }">
            <el-button size="small" @click="handleViewDetail(row)">详情</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination">
        <el-pagination
          v-model:current-page="pagination.current"
          v-model:page-size="pagination.size"
          :total="pagination.total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 日志详情对话框 -->
    <el-dialog
      v-model="detailDialogVisible"
      title="任务日志详情"
      width="60%"
    >
      <el-descriptions :column="1" border>
        <el-descriptions-item label="任务ID">{{ currentLog.id }}</el-descriptions-item>
        <el-descriptions-item label="任务名称">{{ currentLog.taskName }}</el-descriptions-item>
        <el-descriptions-item label="开始时间">{{ currentLog.startTime }}</el-descriptions-item>
        <el-descriptions-item label="结束时间">{{ currentLog.endTime }}</el-descriptions-item>
        <el-descriptions-item label="状态">
          <el-tag :type="statusTagType(currentLog.status)">
            {{ formatStatus(currentLog.status) }}
          </el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="执行参数">
          <pre>{{ formatJson(currentLog.params) }}</pre>
        </el-descriptions-item>
        <el-descriptions-item label="执行结果">
          <pre>{{ currentLog.message }}</pre>
        </el-descriptions-item>
      </el-descriptions>
    </el-dialog>
  </div>
</template>

<script lang="ts" setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import { taskLogApi, type TaskLog } from '@/api/taskLog'

// 搜索表单
const searchForm = reactive({
  taskName: '',
  status: '',
  executeTimeRange: []
})

// 表格数据
const tableData = ref<TaskLog[]>([])
const loading = ref(false)

// 分页配置
const pagination = reactive({
  current: 1,
  size: 10,
  total: 0
})

// 详情对话框
const detailDialogVisible = ref(false)
const currentLog = ref<Partial<TaskLog>>({})

// 格式化状态
const formatStatus = (status: string) => {
  const statusMap: Record<string, string> = {
    SUCCESS: '成功',
    FAILED: '失败',
    RUNNING: '运行中'
  }
  return statusMap[status] || status
}

// 状态标签类型
const statusTagType = (status: string) => {
  const typeMap: Record<string, string> = {
    SUCCESS: 'success',
    FAILED: 'danger',
    RUNNING: 'warning'
  }
  return typeMap[status] || ''
}

// 格式化JSON
const formatJson = (json: string) => {
  try {
    return JSON.stringify(JSON.parse(json), null, 2)
  } catch {
    return json
  }
}

// 获取任务日志列表
const getList = async () => {
  loading.value = true
  try {
    const params = {
      ...searchForm,
      current: pagination.current,
      size: pagination.size
    }
    
    if (searchForm.executeTimeRange?.length === 2) {
      params.startTime = searchForm.executeTimeRange[0]
      params.endTime = searchForm.executeTimeRange[1]
    }

    const { data } = await taskLogApi.fetchTaskLogs(params)
    tableData.value = data.list
    pagination.total = data.total
  } catch (error) {
    ElMessage.error('获取任务日志失败')
    console.error(error)
  } finally {
    loading.value = false
  }
}

// 搜索
const handleSearch = () => {
  pagination.current = 1
  getList()
}

// 重置搜索
const resetSearch = () => {
  searchForm.taskName = ''
  searchForm.status = ''
  searchForm.executeTimeRange = []
  handleSearch()
}

// 分页大小变化
const handleSizeChange = (size: number) => {
  pagination.size = size
  getList()
}

// 当前页变化
const handleCurrentChange = (current: number) => {
  pagination.current = current
  getList()
}

// 查看日志详情
const handleViewDetail = (row: TaskLog) => {
  currentLog.value = { ...row }
  detailDialogVisible.value = true
}

onMounted(() => {
  getList()
})
</script>

<style scoped>
.task-log-container {
  padding: 20px;
}

.search-card {
  margin-bottom: 20px;
}

.pagination {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

pre {
  margin: 0;
  white-space: pre-wrap;
  word-wrap: break-word;
}
</style>
